<template>
  <div>
    <div class="card" style="margin-bottom: 5px">
      <el-input clearable @clear="load" style="width: 260px;margin-right:5px" v-model="data.username"
                placeholder="请输入账号查询" :prefix-icon="Search"></el-input>
      <el-input clearable @clear="load" style="width: 260px;margin-right:5px" v-model="data.name"
                placeholder="请输入名称查询" :prefix-icon="Search"></el-input>
      <el-button type="primary" @click="load">查 询</el-button>
      <el-button @click="reset">重 置</el-button>

    </div>
    <div class="card" style="margin-bottom: 5px">
      <el-button type="primary" @click="handleAdd">新 增</el-button>
      <el-button type="danger" @click="deleteBatch">批量删除</el-button>
      <el-button type="info" @click="exportData">批量导出</el-button>
      <el-upload
          style="display: inline-block; margin-left: 13px"
          action="http://localhost:8081/admin/import"
          :show-file-list="false"
          :on-success="handleImportSuccess"
      >
        <el-button type="success">批量导入</el-button>
      </el-upload>


    </div>
    <div class="card" style="margin-bottom: 5px">
      <el-table :data="data.tableData" style="width: 100%" @selection-change="handleSelectionChange"
                :header-cell-style="{ color: '#333', backgroundColor: '#eaf4ff' }">
        <el-table-column type="selection" width="55"/>
        <el-table-column prop="username" label="账号"/>
        <el-table-column prop="name" label="名称"/>
        <el-table-column prop="phone" label="电话"/>
        <el-table-column prop="email" label="邮箱"/>
        <el-table-column label="操作" width="100">
          <template #default="scope">
          <el-button type="primary" icon="Edit" circle @click="handleEdit(scope.row)"></el-button>
          <el-button type="danger" icon="Delete" circle @click="del(scope.row.id)"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!--    分页-->
    <div class="card">
      <el-pagination
          v-model:current-page="data.pageNum"
          v-model:page-size="data.pageSize"
          :page-size="data.pageSize"
          layout="total, sizes,prev, pager, next,jumper"
          :page-sizes="[5,10,20]"
          :total="data.total"
          @current-change="load"
          @size-change="load"

      />
    </div>                                                              //去除历史残留记录
    <el-dialog v-model="data.formVisible" title="管理员信息" width="500" destroy-on-close="">
      <el-form ref="formRef" :model="data.form" :rules="data.rules" label-width="80px" style="padding: 20px 30px 10px 0">
        <el-form-item prop="username" label="账号">
          <el-input v-model="data.form.username" autocomplete="off" placeholder="请输入账号"/>
        </el-form-item>
        <el-form-item prop="name" label="名称">
          <el-input v-model="data.form.name" autocomplete="off" placeholder="请输入名称"/>
        </el-form-item>
        <el-form-item prop="phone" label="电话">
          <el-input v-model="data.form.phone" autocomplete="off" placeholder="请输入电话"/>
        </el-form-item>
        <el-form-item prop="email" label="邮箱">
          <el-input v-model="data.form.email" autocomplete="off" placeholder="请输入邮箱"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="data.formVisible = false">取 消</el-button>
          <el-button type="primary" @click="save">保 存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>

</template>

<script setup>
import {reactive,ref} from "vue";
import {Search} from "@element-plus/icons-vue";
// import axios from 'axios';
import request from "@/until/request.js";
import {ElMessage, ElMessageBox} from "element-plus";

const data = reactive({
  username: null,
  name: null,
  pageNum: 1,
  pageSize: 5,
  total: 0,
  tableData: [],
  formVisible: false,
  form: {},
  rules: {
    username: [
      {required: true, message: '请填写账号', trigger: 'blur'}
    ],
    name: [
      {required: true, message: '请填写名称', trigger: 'blur'}
    ],
    phone: [
      {required: true, message: '请填写电话', trigger: 'blur'}
    ],
    email: [
      {required: true, message: '请填写邮箱', trigger: 'blur'}
    ]
  },
  rows: []
});

const formRef = ref()

const load = () => {
  request.get('/admin/selectPage', {
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      name: data.name,
      username: data.username
    }
  }).then(res => {
    if (res.code === '200') {
      data.tableData = res.data.list
      data.total = res.data.total
    } else {
      ElMessage.error(res.msg)
    }
  });
};

// 重置函数
const reset = () => {
  data.name = null;
  data.username = null; // 重置账号输入
  data.pageNum = 1; // 重置后回到第一页
  load();
};
load();
//新增
const handleAdd = () => {
  data.formVisible = true
  data.form = {}
};

const add = () => {
  // formRef 表单的引用
  formRef.value.validate((valid) => {
    if (valid) { //验证通过的情况下
      request.post('/admin/add', data.form).then((res) => {
        if (res.code === '200') {
          data.formVisible = false;
          ElMessage.success('新增成功');
          load();
        } else {
          ElMessage.error(res.msg);
        }
      });
    }
  });
};

//编辑
const handleEdit = (row) => {
  data.form = JSON.parse(JSON.stringify(row)) //深度拷贝
  data.formVisible = true
};

const update = () => {
  // formRef 表单的引用
  formRef.value.validate((valid) => {
    if (valid) { //验证通过的情况下
      request.put('/admin/update', data.form).then((res) => {
        if (res.code === '200') {
          data.formVisible = false;
          ElMessage.success('修改成功');
          load();
        } else {
          ElMessage.error(res.msg);
        }
      });
    }
  });
}

//兼容新增和修改
const save = () => {
  data.form.id ? update() : add()
}

const del = (id) =>{
  ElMessageBox.confirm('删除后无法回复，您确认删除该数据吗？','删除确认',{type: 'warning'}).then(res =>
  {

    request.delete('/admin/delete/ ' + id).then((res) => {
      if (res.code === '200') {
        data.formVisible = false;
        ElMessage.success('删除成功');
        load();
      } else {
        ElMessage.error(res.msg);
      }
    });
   }).catch(err =>{})
}

const handleSelectionChange = (rows) => {
 data.rows =rows
}
const deleteBatch = () => {
  if (data.rows.length === 0){
    ElMessage.warning('请选择数据')
    return
  }
  ElMessageBox.confirm('删除后无法回复，您确认删除该数据吗？','删除确认',{type: 'warning'}).then(res =>
  {

    request.delete('/admin/deleteBatch',{data: data.rows} ).then((res) => {
      if (res.code === '200') {
        data.formVisible = false;
        ElMessage.success('批量删除成功');
        load();
      } else {
        ElMessage.error(res.msg);
      }
    });
  }).catch(err =>{})
}
const exportData = () =>{
  let url = `http://localhost:8081/admin/export?username=${data.username === null ? '' : data.username}&name=${data.name === null ? '' : data.name}`
  window.open(url)
}
const handleImportSuccess = (res) => {
  if (res.code === '200') {
    ElMessage.success("批量导入成功");
    load()
  } else {
    ElMessage.error(res.msg);
  }
}
</script>
// axios.get('http://localhost:8081/admin/selectAll').then(res => {
//  if (res.code !== 200){
//  //   错误提示
//  } else {
//    console.log(res.data.data)
//  }
// })
/*
request.get('/admin/selectAll').then(res =>{
if (res.code ===200){
console.log(res)
}else {
ElMessage.error(res.msg)
}
})
*/



